package org.anupta.realm.server.inter;

import org.anupta.realm.main.Main;
import org.anupta.realm.server.inter.client.InterClient;
import org.anupta.realm.server.realm.client.RealmClient;
import org.anupta.realm.server.realm.packet.login.answer.HostList;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

public class InterHandler extends IoHandlerAdapter {
	@Override
    public void sessionOpened(IoSession session) throws Exception {
		Main.out.println(new StringBuilder("GameServer connection : ").append(session.getRemoteAddress()).toString());
        session.setAttribute("client", new InterClient(session));
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            if(message instanceof IoBuffer){
            	IoBuffer buffer = IoBuffer.allocate(2048);
            	buffer.put((IoBuffer)message);
            	buffer.flip();
            	client.parse(buffer);
            }
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            client.quit();
        }
        for(IoSession sess : Main.realm.getAllSession().values()){
			if(sess.getAttribute("client") instanceof RealmClient){
				RealmClient client = (RealmClient) sess.getAttribute("client");
				new HostList(client);
				continue;
			}
		}
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof InterClient) {
            InterClient client = (InterClient) objC;
            client.quit();
        }
    }
}
